package com.oner365.test.apk;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.IOUtils;

public class ZipWithPassword {

  public static void main(String[] args) {
    String sourceFile = "/Users/taoliu/Downloads/feature-ylk-20240501";
    String zipFileName = "/Users/taoliu/Downloads/compressed.zip";
    String password = "12345678901112131415161718192021";

    // 压缩文件
    try {
      compressWithPassword(sourceFile, zipFileName, password);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void compressWithPassword(String sourceFile, String zipFileName, String password) throws IOException {
    try (FileInputStream fis = new FileInputStream(sourceFile);
        FileOutputStream fos = new FileOutputStream(zipFileName);
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos)) {

      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(password.getBytes(), "AES"));
      CipherOutputStream cos = new CipherOutputStream(fos, cipher);

      zos.setLevel(Deflater.DEFAULT_COMPRESSION);
      zos.putArchiveEntry(new ZipArchiveEntry(sourceFile));

      IOUtils.copy(fis, cos);

      cos.close();
      zos.closeArchiveEntry();
      zos.finish();

      System.out.println("File compressed successfully!");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
